package example;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import java.io.File;


/**
 * 支绍昆 2018/10/12 0012
 */
public class FileUploadClient {

    public void connect(int port, String host, final FileUpload fileUpload) throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap boot = new Bootstrap();
            boot
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new ObjectEncoder());
                            channel.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                            channel.pipeline().addLast(new FileUploadClientHandler(fileUpload));
                        }
                    });
            ChannelFuture cf = boot.connect(host, port).sync();
            cf.channel().closeFuture().sync();
            System.out.println("file upload connect end");
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 7000;
        if (args != null && args.length > 0){
            port = Integer.parseInt(args[0]);
        }
        try {
            File file = new File("D:\\桌面背景\\6dfe2d1ad80316e19704faa6b419a8e6.jpg");

            FileUpload fileUpload = new FileUpload();
            fileUpload.setFile(file);
            fileUpload.setName(file.getName());
            fileUpload.setStarPos(0);

            new FileUploadClient().connect(port, "127.0.0.1", fileUpload);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
